﻿using Liang.DataBase.BLL;
using Liang.DataBase.Model.Entity;
using Liang.DataBase.Tools;
using Liang.UI;
using Liang.UI.Enums;
using Liang.Util;
using Liang.Resource;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using Client.Helper;
using Liang.DataBase.Helper;

namespace Client
{
    public partial class FrmLogin : Form
    {
        ToolTip toolTip = null;

        public FrmLogin()
        {
            InitializeComponent();
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {
            this.comName.DrawMode = DrawMode.OwnerDrawFixed;
            this.comName.DrawItem += new DrawItemEventHandler(cb_DrawItem);
            this.comName.DropDownClosed += new EventHandler(cb_DropDownClosed);
            //this.Controls.Add(this.comName);
            this.toolTip = new ToolTip();
            this.toolTip.SetToolTip(this.comName, "账号");

            initView();
            initUsers();
            InitLastLogin();
            this.Text = Liang.Model.Const.PROJECT_NAME;
        }

        /// <summary>
        /// 初始化图片背景
        /// </summary>
        void initView()
        {
            //Bitmap img = (Bitmap)pictbox.Image;
            //GraphicsPath grapth = GetNoneTransparentRegion(img, 10);
            //this.Region = new Region(grapth);

            //要显示的图片设置为窗体背景；
            this.BackgroundImage = AssemblyHelper.GetImage("KeyerResource", "Image.login.login.png");
            this.BackgroundImageLayout = ImageLayout.Stretch;

            //在修改窗体尺寸之前设置窗体为无边框样式；
            //this.FormBorderStyle = FormBorderStyle.None;
            //this.Width = pictbox.Image.Width;
            //this.Height = pictbox.Image.Height;
        }

        void initUsers()
        {
            UserBLL userBLL = new UserBLL();
            IList<sys_user> list = userBLL.FindAll();
            this.comName.DataSource = list;
            this.comName.DisplayMember = "loginName";
            this.comName.ValueMember = "userId";
        }

        /// <summary>
        /// 读取位图的非透明区域，返回指定图片中的非透明区域；
        /// </summary>
        /// <param name="img">位图</param>
        /// <param name="alpha">alpha 小于等于该值的为透明</param>
        /// <returns></returns>
        GraphicsPath GetNoneTransparentRegion(Bitmap img, byte alpha)
        {
            int height = img.Height;
            int width = img.Width;

            int xStart, xEnd;
            GraphicsPath grpPath = new GraphicsPath();
            for (int y = 0; y < height; y++)
            {
                //逐行扫描；
                for (int x = 0; x < width; x++)
                {
                    //略过连续透明的部分；
                    while (x < width && img.GetPixel(x, y).A <= alpha)
                    {
                        x++;
                    }
                    //不透明部分；
                    xStart = x;
                    while (x < width && img.GetPixel(x, y).A > alpha)
                    {
                        x++;
                    }
                    xEnd = x;
                    if (img.GetPixel(x - 1, y).A > alpha)
                    {
                        grpPath.AddRectangle(new Rectangle(xStart, y, xEnd - xStart, 1));
                    }
                }
            }
            return grpPath;
        }

        /// <summary>
        /// 校验输入
        /// </summary>
        /// <returns></returns>
        bool validate()
        {
            if (null == comName.SelectedItem)
            {
                MessageBoxEx.Show(this, "请输入账号", "提示", MessageBoxIconEx.Information, MessageBoxButtonsEx.OKCancel);
                this.comName.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(txtPwd.Text))
            {
                MessageBoxEx.Show(this, "请输入密码", "提示", MessageBoxIconEx.Warning, MessageBoxButtonsEx.OKCancel);
                this.txtPwd.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// 登陆
        /// </summary>
        void Login()
        {
            if (validate())
            {
                sys_user tmp = (sys_user)comName.SelectedItem;
                string strUserName = tmp.name;
                string strLoginName = tmp.loginName;

                string strPassword = AppHelper.EncPassword(txtPwd.Text);

                if (strPassword.Equals(tmp.password))
                {
                    UserManager.loginedUser = tmp;

                    // 登陆成功
                    if (this.checkBox_remember.Checked)
                    {
                        // 记住当前账号登陆信息
                        SaveLastLogin();
                    }

                    NotifyForm.AnimalShow("消息提示", string.Format("{0}登录系统成功", strUserName));
                    LogHelper.WriteLog(typeof(FrmLogin), string.Format("用户：{0}登录系统", strUserName), 2);

                    this.Close();
                }
                else
                {
                    UserManager.loginedUser = null;
                    LogHelper.WriteLog(typeof(FrmLogin), string.Format("账号：{0}登录系统失败", strUserName), 2);
                    MessageBoxEx.Show(this, "账号或密码错误", "错误", MessageBoxIconEx.Error, MessageBoxButtonsEx.OK);
                }
            }
        }

        /// <summary>
        /// 记住最后一个登陆的用户
        /// </summary>
        void SaveLastLogin()
        {
            FileStream fs = new FileStream("loginDate", FileMode.Create);
            BinaryFormatter bf = new BinaryFormatter();
            if (null != UserManager.loginedUser)
            {
                bf.Serialize(fs, UserManager.loginedUser);
            }
            fs.Close();
        }

        /// <summary>
        /// 读取最后一个登陆用户的信息
        /// </summary>
        void InitLastLogin()
        {
            FileStream fs = new FileStream("loginDate", FileMode.OpenOrCreate);
            if (fs.Length > 0)
            {
                BinaryFormatter bf = new BinaryFormatter();
                sys_user tmpUser = (sys_user)bf.Deserialize(fs);
                comLoadUserByValue(this.comName, tmpUser.userId);
                txtPwd.Text = AppHelper.DecPassword(tmpUser.password);
                this.checkBox_remember.Checked = true;
            }
            fs.Close();
        }

        void comLoadUserByValue(ComboBox cb, object userId)
        {
            for (int i = 0; i < cb.Items.Count; ++i)
            {
                sys_user o = (sys_user)cb.Items[i];
                if (o.userId.Equals(userId))
                {
                    cb.SelectedIndex = i;
                    break;
                }
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            Login();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (MessageBoxEx.Show(this, "确定退出吗？", "提示", MessageBoxIconEx.Question, MessageBoxButtonsEx.OKCancel) == DialogResult.OK)
            {
                System.Environment.Exit(0);
            }
        }

        private void txtName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtPwd.Focus();
            }
        }

        private void txtPwd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Login();
            }
        }

        private void comName_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 改变了选择，清空密码
            txtPwd.Text = string.Empty;
        }

        void cb_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
        {
            // 绘制背景
            e.DrawBackground();
            // 绘制列表项目
            sys_user tmp = (sys_user)this.comName.Items[e.Index];
            e.Graphics.DrawString(tmp.loginName, e.Font, System.Drawing.Brushes.Black, e.Bounds);
            // 将高亮的列表项目的文字传递到toolTip1(之前建立ToolTip的一个实例)
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            {
                this.toolTip.Show(tmp.name, this, this.comName.Location.X + e.Bounds.Width, this.comName.Location.Y);
            }
            e.DrawFocusRectangle();
        }

        void cb_DropDownClosed(object sender, EventArgs e)
        {
            this.toolTip.Hide(this.comName);
        }
    }
}
